<template>
  <div>
    <el-card style="margin-top:20px;">
      <el-form label-width="300px" inline style="margin-bottom:15px;">
        <el-form-item>
          <el-input
            v-model="userName"
            placeholder="用户名"
            @input="trimValue"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchHandler"
          ></el-button>
          <el-button type="info" @click="clearIptValue">清空</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom:20px;">
        <el-button type="primary" @click="addUser">添加</el-button>
        <el-button
          type="danger"
          @click="removeUsers"
          :disabled="checkedList.length === 0"
          >批量删除</el-button
        >
      </div>

      <el-table
        :data="userInfo"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="selectionHandler"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="nickName" label="用户昵称"> </el-table-column>
        <el-table-column prop="roleName" label="角色列表"> </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间"> </el-table-column>
        <el-table-column prop="gmtModified" label="更新时间"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="info"
              title="分配角色"
              icon="el-icon-s-custom"
              style="width:50px;height:40px;"
              @click="setUserRole(row)"
            ></el-button>
            <el-button
              type="primary"
              title="修改用户"
              icon="el-icon-edit-outline"
              style="width:50px;height:40px;"
              @click="updateUser(row)"
            ></el-button>
            <el-popconfirm
              :title="`确定要开除${row.username}吗？`"
              @onConfirm="removeUser(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  title="删除角色"
                  icon="el-icon-delete-solid"
                  style="width:50px;height:40px;"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        layout="total, prev, pager, next,->, jumper,sizes"
        :total="total"
        :page-size.sync="size"
        :current-page.sync="current"
        :page-sizes="[5, 10, 15]"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      :title="formData.id ? '修改用户信息' : '新增用户信息'"
      :visible.sync="dialogVisible"
      @close="addFormClose"
    >
      <el-form label-width="100px" :model="formData" ref="userForm">
        <el-form-item
          label="用户名"
          prop="username"
          :rules="{
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          }"
        >
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="formData.nickName"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!formData.id"
          label="密码"
          prop="password"
          :rules="{
            required: true,
            message: '用户名不能为空且不少于6个字符',
            min: 6,
            trigger: 'blur'
          }"
        >
          <el-input v-model="formData.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addUserList" v-loading="isloading"
          >提交</el-button
        >
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置权限" :visible.sync="dialogRoleVisible">
      <el-form label-width="100px">
        <el-form-item label="用户名">
          <el-input disabled :value="formData.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="userRoleIds"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="item in allRoles"
              :key="item.id"
              :label="item.id"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="addRole" v-loading="btnLoading"
          >保存</el-button
        >
        <el-button @click="dialogRoleVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import * as aclApis from "@/api/acl";
import { MessageBox } from "element-ui";
export default {
  name: "user",
  data() {
    return {
      userName: "",
      userInfo: [],
      total: 0,
      size: 5,
      current: 1,
      dialogVisible: false,
      loading: false,
      formData: {
        username: "",
        nickName: "",
        password: ""
      },
      isloading: false,
      checkedList: [],
      dialogRoleVisible: false,
      allRoles: [], //所有身份
      userRoleIds: [], //当前身份的id
      checkAll: false, // 是否全选
      isIndeterminate: false, //是否全选
      btnLoading: false
    };
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    /* 获取分页数据 */
    async getUserInfo() {
      try {
        this.loading = true;
        const res = await aclApis.reqUserInfo(
          this.current,
          this.size,
          this.userName
        );
        this.userInfo = res.data.items;
        this.total = res.data.total;
      } catch (e) {
        this.$message.error("获取管理用户分页列表失败");
      } finally {
        this.loading = false;
      }
    },
    /* 输入去空格 */
    trimValue() {
      this.userName = this.userName.replace(/\s+/g, "");
    },
    /*点击搜索 搜索数据 */
    searchHandler() {
      this.getUserInfo();
    },
    /* 点击重置 */
    clearIptValue() {
      if (this.userName == "") return;
      this.userName = "";
      this.getUserInfo();
    },

    /* 添加用户 */
    addUser() {
      this.dialogVisible = true;
      if (this.formData.id) {
        this.formData = {
          username: "",
          nickName: "",
          password: ""
        };
      }
    },
    /* 对话框关闭 清除校验 */
    addFormClose() {
      this.$refs.userForm.clearValidate();
    },

    /* 添加 */
    async addUserList() {
      const userType = this.formData.id ? "修改" : "新增";
      try {
        await this.$refs.userForm.validate();

        this.isloading = true;
        if (this.formData.id) {
          await aclApis.reqUpdateUser(this.formData);
        } else {
          await aclApis.reqAddUser(this.formData);
        }
        this.getUserInfo();
        this.dialogVisible = false;
        this.$message.success(userType + "成功");
      } catch (e) {
        if (e != false) {
          this.$message.error(userType + "提交失败");
        }
      } finally {
        this.isloading = false;
      }
    },
    /* 点击编辑 */
    updateUser(data) {
      console.log("", data);

      this.dialogVisible = true;
      this.formData = { ...data };
    },
    /* 删除单个 */
    async removeUser(id) {
      try {
        await aclApis.reqRemoveUser(id);
        this.getUserInfo();
        this.$message.success("删除成功");
      } catch (e) {
        if (e != "cancel") {
          this.$message.error("删除失败");
        }
      }
    },
    /* 表格内数据选中框变化事件 */
    selectionHandler(data) {
      this.checkedList = data.map(item => item.id);
    },
    /* 多选删除 */
    async removeUsers() {
      try {
        await MessageBox.confirm("确定要删除吗", "提示", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",

          type: "warning"
        });
        await aclApis.reqRemoveUsers(this.checkedList);
        this.$message.success("删除成功");
        this.getUserInfo();
      } catch (e) {
        this.$message.error("多选删除失败");
      }
    },
    /* 点击查看展开dialog */
    async setUserRole(row) {
      try {
        this.formData = row;
        this.dialogRoleVisible = true;
        const res = await aclApis.reqUserRoleList(row.id);
        const { allRolesList, assignRoles } = res.data;
        this.allRoles = allRolesList;
        this.userRoleIds = assignRoles.map(item => item.id);
        this.checkAll = allRolesList.length === assignRoles.length;
        this.isIndeterminate =
          assignRoles.length > 0 && assignRoles.length < allRolesList.length;
      } catch (e) {
        this.$message.error("获取用户信息失败");
      }
    },
    /* 点击全选 */
    handleCheckAllChange(value) {
      this.userRoleIds = value ? this.allRoles.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    /* 角色列表选项发生改变监听 */
    handleCheckedChange() {
      this.checkAll =
        this.userRoleIds.length === this.allRoles.length &&
        this.allRoles.length > 0;
      this.isIndeterminate =
        this.userRoleIds.length > 0 &&
        this.userRoleIds.length < this.allRoles.length;
    },
    async addRole() {
      try {
        const userId = this.formData.id;
        const roleId = this.userRoleIds.join(",");
        this.btnLoading = true;
        await aclApis.reqAddUserRole(userId, roleId);
        this.$message.success("保存成功");
        this.dialogRoleVisible = false;
        this.getUserInfo();
      } catch (e) {
        this.$message.error("保存失败");
      } finally {
        this.btnLoading = false;
      }
    }
  },
  watch: {
    current() {
      this.getUserInfo();
    },
    size() {
      this.getUserInfo();
    }
  }
};
</script>

<style></style>
